package com.nnAdmin.controller;

import com.nn.R;
import com.nn.entity.LoginUser;
import com.nn.entity.SysUser;
import com.nn.service.AdminLoginService;
import com.nn.service.SysMenuService;
import com.nn.service.SysRoleService;
import com.nn.utils.BeanCopyUtils;
import com.nn.utils.SecurityUtils;
import com.nn.vo.AdminUserInfoVo;
import com.nn.vo.RoutersVo;
import com.nn.vo.UserInfoVO;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 年年
 * @// TODO: 2022/11/18
 *
 */

@RestController
public class UserController {

    @Resource
    private AdminLoginService adminLoginService;


    @Resource
    private SysMenuService menuService;

    @Resource
    private SysRoleService roleService;

    /**
     * 后台登录接口
     * @return
     */
    @PostMapping("/user/login")
    public R login(@RequestBody SysUser user){
        if(!StringUtils.hasText(user.getUserName()))
            throw new RuntimeException("用输入用户名");
        return adminLoginService.login(user);
    }


    /**
     * 退出登录
     * @return
     */
    @PostMapping("/user/logout")
    public R logout(){
        return adminLoginService.logout();
    }

    /**
     * 获取权限信息
     * @return
     */
    @GetMapping("/getInfo")
    public R<AdminUserInfoVo> getInfo(){
        //查当前登录的用户的对应信息
        LoginUser user = SecurityUtils.getLoginUser();
        //根据id查询权限信息
       List<String> perms =  menuService.selectPermsByUserId(user.getUser().getId());
        //根据用户id查寻角色信息
        List<String> roleList = roleService.selectRoleKeyByUserId(user.getUser().getId());
        //封装数据返回
        SysUser UserInfo = user.getUser();
        UserInfoVO userInfoVO = BeanCopyUtils.copyBean(UserInfo, UserInfoVO.class);
        AdminUserInfoVo adminUserInfoVo = new AdminUserInfoVo(perms,roleList,userInfoVO);
        return R.okResult(adminUserInfoVo);
    }


    /**
     * 菜单动态路由
     * @return
     */
    @GetMapping("/getRouters")
    public R<RoutersVo> getRouters(){
        RoutersVo result = menuService.selectRouterMenuTreeByUserId();
        return R.okResult(result);
    }
}
